/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sk.lieskove.jianghongtiao.common.extract.text;

import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.EditorKit;
import java.io.*;

/**
 * 
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
public class Rtf2Text implements Serializable, TextExtractor {

    private transient Logger log = Logger.getLogger(Rtf2Text.class);
    private transient PropertiesUtils pu = new PropertiesUtils(Rtf2Text.class);

    @Override
    public String extractText(File inputFile) {
        log.debug("Enter Rtf2Text with file: "+inputFile.getAbsolutePath());
        return rtfToHtml(inputFile);
    }

    private String rtfToHtml(File inputFile) {
        Reader rtf = null;
        try {
            rtf = new FileReader(inputFile);
            JEditorPane p = new JEditorPane();
            p.setContentType("text/rtf");
            EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
            try {
                kitRtf.read(rtf, p.getDocument(), 0);
                kitRtf = null;
                EditorKit kitHtml = p.getEditorKitForContentType("text/html");
                Writer writer = new StringWriter();
                kitHtml.write(writer, p.getDocument(), 0, p.getDocument().getLength());
                Xml2Text xml2Text = new Xml2Text();
                String extractedText = xml2Text.extractText(writer.toString().trim()).trim();
                log.debug("Rtf2Text extracted: "+extractedText.length()+" characters.");
                return extractedText;
            } catch (IOException ex) {
                log.error("Exception thrown while reading file: "+inputFile.getAbsolutePath(), ex);
            } catch (BadLocationException e) {
                log.error("Bad location. file: "+inputFile.getAbsolutePath(), e);
            }
        } catch (FileNotFoundException ex) {
            log.error("File was not found: "+inputFile.getAbsolutePath());
        } finally {
            try {
                rtf.close();
            } catch (IOException ex) {
                log.error("Cannot close file: "+inputFile.getAbsolutePath());
            }
        }
        return null;
    }
}
